package com.fyd.mybatis.binding;

import cn.hutool.core.lang.ClassScanner;
import com.fyd.mybatis.session.SqlSession;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author fanyudong
 * @date 2025/6/3
 * @description 映射器注册机
 * @copyright 2025  35岁财富自由公司. All rights reserved.
 */
public class MapperRegistry {
    /**
     * 将已经添加的映射器代理工厂加入到 hashMap
     */
    private final Map<Class<?>,MapperProxyFactory<?>> knownMappers = new HashMap<>();

    /**
     * 获取映射器
     * @param type
     * @param sqlSession
     * @return
     * @param <T>
     */
    public <T> T getMapper(Class<T> type, SqlSession sqlSession){
        MapperProxyFactory<T> mapperProxyFactory =  (MapperProxyFactory<T>)knownMappers.get(type);
        if (mapperProxyFactory == null){
            throw new RuntimeException("Type "+type + "is not known to the MapperRegistry.");
        }
        try {
            return mapperProxyFactory.newInstance(sqlSession);
        } catch (Exception e){
            throw new RuntimeException("Error getting mapper instance. Cause: " + e, e);
        }
    }

    /**
     * 添加映射器代理工厂
     * @param type
     * @param <T>
     */
    public <T> void addMapper(Class<T> type){
        if (type.isInterface()){
            if (hasMapper(type)){
                // 如果重复添加了，报错
                throw new RuntimeException("Type " + type + " is already known to the MapperRegistry.");
            }
            // 注册映射器代理工厂
            knownMappers.put(type,new MapperProxyFactory<>(type));
        }
    }

    private <T> boolean hasMapper(Class<T> type) {
        return knownMappers.containsKey(type);
    }
    public void addMappers(String packageName){
        Set<Class<?>> mapperSet = ClassScanner.scanPackage(packageName);
        for (Class<?> mapperClass : mapperSet) {
            addMapper(mapperClass);
        }
    }

}
